<?php

namespace app\api\controller\zi;

use addons\shopro\library\PayService;
use addons\shopro\model\User;
use addons\shopro\model\UserOauth;
use app\api\model\OrderM;
use app\common\controller\Api;
use app\api\model\store\StoreProductcs;
use app\common\model\Share;
use think\Db;
use think\Validate;

class Wxcy extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private static function getWx($info)
    {
        $wx = '';
        $tgdzri = mb_substr($info['TianGanDiZhiDay'], -1, 1, "utf-8");
        if ($tgdzri == '寅') {
            $wx = '木';
        }
        if ($tgdzri == '卯') {
            $wx = '木';
        }
        if ($tgdzri == '午') {
            $wx = '火';
        }
        if ($tgdzri == '巳') {
            $wx = '火';
        }
        if ($tgdzri == '申') {
            $wx = '金';
        }
        if ($tgdzri == '酉') {
            $wx = '金';
        }
        if ($tgdzri == '子') {
            $wx = '水';
        }
        if ($tgdzri == '亥') {
            $wx = '水';
        }
        if ($tgdzri == '辰' || $tgdzri == '戌' || $tgdzri == '丑' || $tgdzri == '未') {
            $wx = '土';
        }
        return $wx;
    }

    public function wxcy()
    {
        $date = explode("-", request()->get('date', date("Y-m-d")));

        $nowyear = $date[0];
        $nowmonth = $date[1];
        $nowday = $date[2];
        $nowriqi = $nowmonth . '/' . $nowday . '/' . $nowyear . ' 12:00:00.000 AM';
        $info = Db::name('calendar')->where('GregorianDateTime', $nowriqi)->find();

        $daJi = null;
        $ciJi = null;
        $buYi = null;
        $color = null;
        $zhuji = null;

        $wx = self::getWx($info);

        if ($this->auth->getUser()) {
            if (($this->auth->getUser()->grade == 1 || $this->auth->getUser()->grade == 2) || Db::name('store_ordersm')->where([
                    'riqi' => $nowyear . '-' . $nowmonth . '-' . $nowday,
                    'status' => 1,
                    'uid' => $this->auth->id
                ])->find()) {
                $colorInfo = Db::name("color")->where('name', $wx)->find();
                $daJi = $colorInfo['one'];
                $ciJi = $colorInfo['two'];
                $buYi = $colorInfo['three'];
                $color = $colorInfo['color'];
                $zhuji = $colorInfo['zhuji'];
            }
        }

        $this->success(null, [
            'price' => config('site.wxcyPrice') ?? 1,
            'dayInfo' => [
                'date' => $date[0] . '-' . $date[1] . '-' . $date[2],
                'calendar' => $info['LMonth'] . $info['LDay'],
                'animals' => $info['LYear'],
                'XingWest' => $info['XingWest'],
                'yi' => $info['Yi'],
                'Ji' => $info['Ji']
            ],
            'payInfo' => [
                'daJi' => $daJi,
                'ciJi' => $ciJi,
                'buYi' => $buYi,
                'color' => $color,
                'zhuji' => $zhuji
            ]
        ]);
    }

    //五行穿衣
    public function creat_orderwxcy()
    {
        checkEnv('yansongda');
        if (empty(input('date'))) {
            $this->error('日期不能为空');
        }

        $date = explode('-', input('date'));
        $user = $this->auth->getUser();
        $openid = UserOauth::where([
            'user_id' => $user['id'],
            'provider' => 'Wechat',
            'platform' => 'wxMiniProgram'
        ])->value('openid');
        if (!$openid) {
            $this->error('error openid');
        }
        $nowyear = $date[0];
        $nowmonth = $date[1];
        $nowday = $date[2];
        $nowriqi = $nowmonth . '/' . $nowday . '/' . $nowyear . ' 12:00:00.000 AM';
        $riqi = $nowyear . '-' . $nowmonth . '-' . $nowday;

        // 判断是否购买
        if (Db::name('store_ordersm')->where([
            'riqi' => $riqi,
            'status' => 1,
            'uid' => $this->auth->id
        ])->find()) {
            $this->error("该日期已购买");
        }

        $info = Db::name('calendar')->where('GregorianDateTime', $nowriqi)->find();
        //获得五行55
        $wx = self::getWx($info);

        $oid = time() . $this->auth->id;
        $price = config('site.wxcyPrice') ?? 1;
        $a = [
            'order_id' => $oid,
            'uid' => $this->auth->id,
            'total_price' => $price,
            'pay_price' => $price,
            'add_time' => time(),
            'status' => 0,
            'is_del' => 0,
            'cs_name' => '五行穿衣',
            'riqi' => $riqi,
            'wxjz' => $wx,
        ];

        $res = Db::name('store_ordersm')->insertGetId($a);

        if ($res) {
            if (input('type', 1) == 1) {
                $params = (new PayService(
                    'wechat',
                    'wxMiniProgram',
                    $this->request->root(true) . '/api/zi/wxcy/callback'
                ))->create([
                    'order_id' => $oid,
                    'out_trade_no' => $oid,
                    'total_fee' => $price,
                    'body' => '单次购买五行穿衣',
                    'openid' => $openid,
                ]);
            } else {
                // 扣除余额
                $user = User::info();

                if (is_null($user)) {
                    // 没有登录，请登录
                    $this->error(__('Please login first'), null, 401);
                }

                User::money(-$price, $user->id, 'wallet_pay', $oid, '', [
                    'order_id' => $oid,
                    'order_sn' => $oid,
                ]);

                $share = new Share();
                $share->add_goods_range($res, $this->auth->id, false,2);

                Db::name('store_ordersm')->where('order_id', $oid)->update([
                    'status' => 1,
                    'pay_time' => time()
                ]);

                $this->success('支付成功');
            }
            $this->success('', [
                'params' => $params,
                'order_id' => $oid
            ]);
        }
    }

    public function callback()
    {
        $pay = new PayService('wechat', 'wxMiniProgram');
        return $pay->notify(function ($data, $pay = null) {
            if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
                return false;
            }
            Db::name('store_ordersm')->where('order_id', $data['out_trade_no'])->update([
                'status' => 1,
                'pay_time' => time(),
            ]);
            //分销
            $order = Db::name('store_ordersm')->where('order_id', $data['out_trade_no'])->find();
            $share = new Share();
            $share->add_goods_range($order['id'], $order['uid'], false,2); 
            // 分配 15% 收益
            $share->add_distribution($order['id'],2);
            return $pay->success()->send();
        });
    }

    public function orderList()
    {
        $page = input('page', 1);
        $search = input('search');

        $query = Db::name('store_ordersm')->where([
            'uid' => $this->auth->id,
            'status' => 1,
        ]);
        if ($search) {
            $query->where('order_id', 'like', $search);
        }
        $list = $query->order('id desc')->paginate(10, ['page' => $page]);
        $this->success('', [
            'lei_ji_ding_dan' => Db::name('store_ordersm')->where(['uid' => $this->auth->id, 'status' => 1])->count(),
            'zong_xiao_fei' => Db::name('store_ordersm')->where(['uid' => $this->auth->id, 'status' => 1])->sum('pay_price'),
            'list' => $list,
        ]);
    }

    public function orderInfo($id) {
        $info = Db::name('store_ordersm')->where([
            'id' => $id,
            'uid' => $this->auth->id,
            'status' => 1
        ])->find();

        if (!$info)
            $this->error('没有该订单');

        $date = explode('-', $info['riqi']);
        $nowyear = $date[0];
        $nowmonth = $date[1];
        $nowday = $date[2];
        $nowriqi = $nowmonth . '/' . $nowday . '/' . $nowyear . ' 12:00:00.000 AM';

        $calendar = Db::name('calendar')->where('GregorianDateTime', $nowriqi)->find();
        $wx = self::getWx($calendar);
        $colorInfo = Db::name("color")->where('name', $wx)->find();
        $daJi = $colorInfo['one'];
        $ciJi = $colorInfo['two'];
        $buYi = $colorInfo['three'];
        $color = $colorInfo['color'];
        $zhuji = $colorInfo['zhuji'];

        $this->success(null, [
            'orderInfo' => $info,
            'dayInfo' => [
                'date' => $date[0] . '-' . $date[1] . '-' . $date[2],
                'calendar' => $calendar['LMonth'] . $calendar['LDay'],
                'animals' => $calendar['LYear'],
                'XingWest' => $calendar['XingWest'],
                'yi' => $calendar['Yi'],
                'Ji' => $calendar['Ji']
            ],
            'payInfo' => [
                'daJi' => $daJi,
                'ciJi' => $ciJi,
                'buYi' => $buYi,
                'color' => $color,
                'zhuji' => $zhuji
            ]
        ]);
    }

    //五行穿衣每日模板消息通知
    public function send()
    {
        $nowyear = date('Y');
        $nowmonth = date('m');
        $nowday = date('d');
        $nowriqi = $nowmonth . '/' . $nowday . '/' . $nowyear . ' 12:00:00.000 AM';
        $info = Db::name('calendar')->where('GregorianDateTime', $nowriqi)->field('LunarDateTime')->find();
        $url = 'http://vip.yzdf.store/wap/store/wxcy.html?id=184';
        $tempid = 'rsnxWJw5qIvzdHDiYPi1J7fW8k9Hz1Ch9_g2LSzLF-E';
        $defaultColor = '';
        $data = [
            'first' => "您预订的五行穿衣已经生成！",
            'keyword1' => '五行穿衣',
            '$nowriqi' => $info['LunarDateTime'],
            'remark' => '点击查看详情'
        ];
        $uidarray = WechatUser::where("subscribe", 1)->field('openid')->select();
        foreach ($uidarray as $key => $value) {
            try {
                $openid = $value['openid'];
            } catch (\Exception $e) {
                continue;
            }
            WechatService::sendTemplate($openid, $tempid, $data, $url, $defaultColor);
        }
    }
}